let HaikangPlayClass = require("./HaikangPlayClass.js");
let initCount = 0;
let Haikang = function (config) {
  let instance = new HaikangPlayClass(config);
  return new Promise((resolve, reject) => {
    //初始化
    let init = function () {
      return new WebControl({
        szPluginContainer: config.id,
        iServicePortStart: 15900,
        iServicePortEnd: 15909,
        szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11", // 用于IE10使用ActiveX的clsid
        cbConnectSuccess: async function () {
          try {
            let { native } = instance;

            if (
              Object.prototype.toString.call(config.callback) ==
              "[object Function]"
            ) {
              //设置回调消息
              native.JS_SetWindowControlCallback({
                cbIntegrationCallBack: config.callback,
              });
              // console.log("设置回调消息");
            }

            //启动插件服务接口
            await native.JS_StartService("window", {
              dllPath: "./VideoPluginConnect.dll",
            });

            //创建插件窗口接口
            await native.JS_CreateWnd(config.id, 0, 0);
            // console.log("创建插件窗口接口");

            //申请公钥
            // await self.setRSA();

            //初始化显示
            instance.initView();
            // console.log("初始化显示");

            //窗口适应
            instance.adaptive();
          } catch (err) {
            console.error(err);
          }

          resolve(instance);
        },
        cbConnectError: function () {
          console.log("启动失败正在尝试重新启动");
          WebControl.JS_WakeUp("VideoWebPlugin://");
          initCount++;
          if (self.initCount < 3) {
            setTimeout(function () {
              init();
            }, 3000);
          } else {
            reject();
            alert("插件启动失败！");
          }
        },
        cbConnectClose: function (bNormalClose) {
          // 异常断开：bNormalClose = false
          // JS_Disconnect正常断开：bNormalClose = true
          console.log("cbConnectClose", bNormalClose);
        },
      });
    };
    instance.native = init();
  }).catch((err) => {
    console.error(err);
  });
};

global.hk = Haikang;
